package io.kiki.sba.registry.server.clientInterface.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.client.pb.ServiceAppMappingRequest;
import io.kiki.sba.registry.server.clientInterface.wrapper.BlacklistWrapperInterceptor;
import io.kiki.sba.registry.server.shared.remoting.RemotingHelper;
import io.kiki.sba.registry.util.StringUtil;
import lombok.NonNull;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


public class ServiceAppMappingPbHandler extends AbstractClientMetadataRequestHandler<ServiceAppMappingRequest> {
    private static final Logger logger = LoggerFactory.getLogger(BlacklistWrapperInterceptor.class);

    @Override
    public void checkParam(@NonNull ServiceAppMappingRequest request) {

        StringUtil.checkNotEmpty(request.getServiceIdsList(), "request.serviceIds");
    }

    @Override
    public Object doHandle(Channel channel, ServiceAppMappingRequest request) {
        List<String> serviceIdsList = request.getServiceIdsList();
        String remoteIp;
        if (channel != null && channel.getRemoteAddress() != null && channel.getRemoteAddress().getAddress() != null) {
            remoteIp = channel.getRemoteAddress().getAddress().getHostAddress();
        } else {
            remoteIp = StringUtils.EMPTY;
        }
        return appRevisionHandlerStrategy.queryApps(serviceIdsList, remoteIp);
    }

    @Override
    protected void logRequest(Channel channel, ServiceAppMappingRequest request) {
        if (logger.isInfoEnabled()) {
            String sb = "[" + this.getClass().getSimpleName() + "] " + "Remote:" + RemotingHelper.getChannelRemoteAddress(channel) + " ServiceCount: " + request.getServiceIdsList().size();
            logger.info(sb);
        }
    }

    @Override
    public Class interest() {
        return ServiceAppMappingRequest.class;
    }
}
